﻿using System.Application;
using System.Collections.Generic;
using System.Domain.Entity;
using System.Domain.IRepository;
using System.Repository;
using System.Repository.Base;
using System.Text;
using Application.Infrastructure;
using Autofac;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Ubiquity.Web.Ioc;

namespace Ubiquity.Web.Filters
{
    public static class Config1
    {
        public static string User = "User";
    }
    public static class HttpRequestExtensions
    {
        public static string GetAbsoluteUri(this HttpRequest request)
        {
            return new StringBuilder()
                //.Append(request.Scheme)
                //.Append("://")
                //.Append(request.Host)
                .Append(request.PathBase)
                .Append(request.Path)
                //.Append(request.QueryString)
                .ToString();
        }
    }
    /// <summary>
    /// 权限拦截器
    /// </summary>
    public class AuthorizeAttribute : ActionFilterAttribute
    {

        //public AuthorizeAttribute(SysOperationLogService service)
        //{ 
        //    LogService = service;
        //}
        public AuthorizeAttribute()
        {
            //var log = Startup.AutofacContainer.Resolve<ILog>();
            //var repository = Startup.AutofacContainer.Resolve<ISysOperationLogRepository>();
            LogService = IocConfig.Resolve<SysOperationLogService>();
        }

        /// <summary>
        /// 忽略标志 
        /// </summary>
        public bool Ignore;
        public AuthorizeAttribute(bool ignore = false)
        {


            Ignore = ignore;
        }

        //public void OnActionExecuted(ActionExecutedContext context)
        //{
        //    //等Controller的Action方法执行完后，通过更改ActionExecutedContext类的Result属性，来替换Action方法返回的Json对象
        //    context.Result = new JsonResult(new { Message = "This is a MyActionFilter message!" });
        //}
        //protected static DbContextOptions ContextOptions =
        //    FactoryProvider.CreateDbContext("Server=.;Initial Catalog=JewelleryManage;User ID=sa;Password=123456;");

        //private static readonly ISysOperationLogRepository SysOperationLogRepository = new SysOperationLogRepository(ContextOptions);

        private SysOperationLogService LogService;// = new SysOperationLogService(new Log(), SysOperationLogRepository);
        //private static readonly SysOperationLogService LogService = new SysOperationLogService();

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //   var s = ((Controller)context.Controller).Request.Protocol;
            var request = ((Controller)context.Controller).Request;
            var url = request.GetAbsoluteUri(); //当前页面的
            var headers = request.Headers;
            //SysOperationLogService.Register();
            //Headers["Accept"]
            //Headers["Accept-Encoding"]
            //Headers["Accept-Language"]
            //Headers["Connection"]
            //Headers["Cookie"]
            //Headers["Host"]
            //Headers["Te"]
            //Headers["User-Agent"]--浏览器
            //Headers["upgrade-insecure-requests"]
            var Ip = ((Controller)context.Controller).HttpContext.Connection.RemoteIpAddress.ToString();

            SysOperationLogEntity logEntity = new SysOperationLogEntity
            {

                Type = OperationLogType.Other.ToString(),
                IpAddress = Ip,
                //Browser = request.UserAgent.Browser,
                //Version = request.Browser.Version,
                Url = url,
                //UserAgent = request.Headers,
                //RequestType = request.RequestType
                UserAgent = headers["User-Agent"],
                RequestType = request.Method
            };
            string mes = "成功";
            logEntity.Result = true;
            logEntity.Description = mes;
            LogService.WriteDbLog(logEntity);
            if (Ignore == false)
            {
                return;
            }
            //1、获取登陆 session
            //2、判断值是否为空 
            //3、为空跳转 日志

            base.OnActionExecuting(context);

            var user = context.HttpContext.Session.GetString(Config1.User);
            if (user == null)
            {
                context.Result = new RedirectResult("/Sign/Index");

            }

            //context.Result = new EmptyResult();//在IActionFilter.OnActionExecuting方法中，context的Result属性只要被赋值了不为null，就不会执行Controller的Action了，也不会执行该IActionFilter拦截器的OnActionExecuted方法，同时在该IActionFilter拦截器之后注册的其它Filter拦截器也都不会被执行了

        }



    }
}